package exchange

import (
	"github.com/garyburd/redigo/redis"
	"time"
	"sync"
	"github.com/ngaut/log"
	"sort"
	"global/constants"
	"global/core"
)

type ExchangeSort struct {
	Pool 		*redis.Pool

	// 交易所 -> 24h总交易额
	exchanges 	map[string]*sortExchangeAmountData
	receive 	chan *sortExchangeAmountData
	
	ticker 		*time.Ticker

	mux 		sync.Mutex
}

func NewExchangeSort(pool *redis.Pool) *ExchangeSort {
	return &ExchangeSort{
		Pool: 		pool,
		exchanges: 	make(map[string]*sortExchangeAmountData),
		ticker: 	time.NewTicker(2 * time.Second),
		receive: 	make(chan *sortExchangeAmountData, 100),
	}
}

func (s *ExchangeSort) Run() {
	go func() {
		for {
			select {
			case data := <-s.receive:
				s.receiveData(data)
			case <- s.ticker.C:
				s.sorts()
			}
		}
	}()
}

func (s *ExchangeSort) sorts() {
	if len(s.exchanges) == 0 { return }
	s.mux.Lock()
	exchagnes := make([]*sortExchangeAmountData, 0)
	for _, v := range s.exchanges {
		exchagnes = append(exchagnes, v)
	}
	s.mux.Unlock()

	conn := s.Pool.Get()
	defer conn.Close()

	sortTypes := []string{constants.SortTypeAsc, constants.SortTypeDesc}
	for _, v := range sortTypes {
		tmp := make([]*sortExchangeAmountData, len(s.exchanges))
		copy(tmp, exchagnes[:])
		if v == constants.SortTypeAsc {
			sort.Slice(tmp, func(i, j int) bool {
				return tmp[i].Amount.LessThan(tmp[j].Amount)
			})
		} else {
			sort.Slice(tmp, func(i, j int) bool {
				return tmp[i].Amount.GreaterThan(tmp[j].Amount)
			})
		}

		exchangeNames := make([]string, 0)
		for _, v := range tmp {
			exchangeNames = append(exchangeNames, v.Exchange)
		}

		if err := core.SaveExchangeSortForAmount(conn, v, exchangeNames); err != nil {
			log.Errorf("Error: %s", err.Error())
		}
	}
}

// 接受数据
func (s *ExchangeSort) receiveData(data *sortExchangeAmountData) {
	s.mux.Lock()
	s.exchanges[data.Exchange] = data
	s.mux.Unlock()
}
